package com.heima.comment.service.impl;

import com.heima.comment.feign.UserFeign;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.model.comment.dtos.CommentRepayDto;
import com.heima.model.comment.dtos.CommentRepayLikeDto;
import com.heima.model.comment.dtos.CommentRepaySaveDto;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vo.ApCommentRepayVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @作者 itcast
 * @创建日期 2020/12/21 15:31
 **/
@Service
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserFeign userFeign;

    @Autowired
    GreenTextScan greenTextScan;

    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto dto) {
        //1. 检查参数
        if(dto.getCommentId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getSize() ==null || dto.getSize() == 0) {
            dto.setSize(20);
        }
        //2. 按照评论id过滤 设置分页和排序
        Criteria criteria = Criteria.where("commentId").is(dto.getCommentId());
        if(dto.getMinLikes()!=null){
            criteria.and("likes").lt(dto.getMinLikes());
        }
        Query query = Query.query(criteria);
        query.limit(dto.getSize());
        query.with(Sort.by(Sort.Direction.DESC,"likes"));
        List<ApCommentRepay> list = mongoTemplate.find(query, ApCommentRepay.class);
        //3 检查用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        //4. 封装数据返回
        // 4.1 未登录直接返回列表数据
        if (user == null || list == null || list.isEmpty()) {
            return ResponseResult.okResult(list);
        }
        // 4.2 登录处理评论回复列表是否点赞
        // 根据评论回复id查询当前用户的所有点赞行为
        List<String> idList = list.stream().map(ApCommentRepay::getId).collect(Collectors.toList());
        Query coomentRepayLikesQuery =
                Query.query(Criteria.where("commentRepayId").in(idList).and("authorId").is(user.getId()));
        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(coomentRepayLikesQuery, ApCommentRepayLike.class);
        // 获取当前登录用户点赞的评论回复Id列表
        Set<String> likeIdList = apCommentRepayLikes.stream().map(ApCommentRepayLike::getCommentRepayId).collect(Collectors.toSet());
        List<ApCommentRepayVo> voList = new ArrayList<>();
        try {
            for (ApCommentRepay commentRepay: list){
                ApCommentRepayVo repayVo = new ApCommentRepayVo();
                // 是否点赞过该 评论回复
                if(likeIdList.contains(commentRepay.getId())){
                    repayVo.setOperation(((short) 0));
                }
                BeanUtils.copyProperties(repayVo,commentRepay);
                voList.add(repayVo);
            }
            return ResponseResult.okResult(voList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {
        // 1. 判断参数是否正确
        if (dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getContent() != null && dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "评论内容不能超过140字");
        }
        // 2. 判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 3. 内容安全过滤

        // 4. 保存评论信息
        ApUser apUser = userFeign.findApUserById(user.getId());
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "当前登录信息有误");
        }
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(apUser.getId());
        apCommentRepay.setAuthorName(apUser.getName());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());
        apCommentRepay.setLikes(0);
        mongoTemplate.insert(apCommentRepay);
        //更新评论的回复数量
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        apComment.setReply(apComment.getReply() + 1);
        mongoTemplate.save(apComment);
        return ResponseResult.okResult();
    }
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDto dto) {
        // 1. 检查参数
        if (dto.getCommentRepayId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 2. 判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 3. 点赞操作
        ApCommentRepay apCommentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);

        int likes = 0;
        if(apCommentRepay!=null){
            // 当前点赞数量
            likes = apCommentRepay.getLikes();
            if(dto.getOperation()==0){
                // 判断是否点过赞
                Query coomentRepayLikesQuery =
                        Query.query(Criteria.where("commentRepayId").is(dto.getCommentRepayId()).and("authorId").is(user.getId()));
                List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(coomentRepayLikesQuery, ApCommentRepayLike.class);
                if(apCommentRepayLikes!=null && !apCommentRepayLikes.isEmpty()){
                    // 不允许重复点赞
                    return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
                }
                // 点赞操作
                // 修改评论回复点赞数量
                apCommentRepay.setLikes(++likes);
                mongoTemplate.save(apCommentRepay);
                // 保存点赞操作
                ApCommentRepayLike apCommentLike = new ApCommentRepayLike();
                apCommentLike.setAuthorId(user.getId());
                apCommentLike.setCommentRepayId(apCommentRepay.getId());
                apCommentLike.setOperation(dto.getOperation());
                mongoTemplate.save(apCommentLike);
            }else if (dto.getOperation()==1){
                // 取消操作
                //更新评论的点赞数量
                apCommentRepay.setLikes(likes < 1 ? 0 : --likes);
                mongoTemplate.save(apCommentRepay);
                // 删除对应点赞行为记录
                mongoTemplate.remove(Query.query(Criteria.where("authorId").is(user.getId()).and("commentRepayId").is(apCommentRepay.getId())), ApCommentRepayLike.class);
            }
        }
        //5.数据返回
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("likes",apCommentRepay.getLikes());
        return ResponseResult.okResult(resultMap);
    }
}
